<!--
  Component - 用户选择弹窗

  @author yudongbo 2020-05-18

  所需父组件传参：
  dialogVisible: true                   (显示开关)
  userList: ['123', '456']              (已选中的用户选项集合)

  父组件需要监听事件：
  selectUser: 选择用户事件(参数为用户对象集合)
  closeDialog: 关闭弹窗事件
-->
<template>
  <el-dialog
    title="选择用户"
    :visible="dialogVisible"
    width="70%"
    top="10vh"
    append-to-body="true"
    :before-close="handleClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    @open="open"
  >
    <el-row v-loading="listLoading">

      <div>
        <!-- 搜索条件 -->
        <el-row type="flex" justify="end">
          <div class="filter-container">
            <el-cascader
              v-model="listQuery.departmentId"
              :options="departmentOptions"
              :props="{ checkStrictly: true, expandTrigger: 'click', label: 'name', value: 'departmentId', emitPath: false }"
              class="filter-item"
              placeholder="所属部门"
              style="width: 200px;"
              clearable
            />
            <el-input v-model="listQuery.realName" class="filter-item" placeholder="姓名" style="width: 200px;" />
            <el-link type="primary" style="margin-left: 10px; font-size: 16px;" icon="el-icon-search" @click="searchList">搜索</el-link>
            <el-link type="primary" style="margin-left: 10px; font-size: 16px;" @click="resetSearchParam">重置</el-link>
          </div>
        </el-row>

        <el-row>
          <!-- 用户 列表 -->
          <el-table
            ref="multipleTable"
            :data="list"
            height="440"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="姓名" prop="realName" :width="150" :show-overflow-tooltip="true" align="center" />
            <el-table-column label="所属部门" prop="depName" :width="150" :show-overflow-tooltip="true" align="center" />
            <el-table-column label="手机号" prop="phone" :width="150" :show-overflow-tooltip="true" align="center" />
            <el-table-column label="邮箱" prop="email" :width="250" :show-overflow-tooltip="true" align="center" />
            <el-table-column label="操作" :width="100" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <el-link type="primary" @click="$emit('selectUser', [scope.row])">选择</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row type="flex" justify="space-between" style="margin-top:15px;">
          <el-link type="primary" style="margin-left: 15px;" @click="handleAdd">批量选择</el-link>
          <!-- 分页 -->
          <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" style="text-align:right;" @pagination="searchList" />
        </el-row>
      </div>

    </el-row>

  </el-dialog>
</template>

<script>
// api
import { queryUserList } from '@/api/userAndRole/sysUser'
import { queryDepartmentList } from '@/api/userAndRole/sysDepartment'

// 水波纹插件
// import waves from '@/directive/waves'
// 分页组件
import Pagination from '@/components/Pagination'

export default {
  name: 'UserSelectDialog',
  components: { Pagination },
  // directives: { waves },
  props: {
    dialogVisible: Boolean,
    userList: {
      type: Array,
      required: false,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      // 常量 - 响应成功码
      responseSuccessCode: 1,
      listLoading: true,
      list: [],
      total: 0,
      listQuery: {
        departmentId: '',
        realName: '',
        page: 1,
        limit: 10
      },
      departmentOptions: []
    }
  },
  methods: {
    /**
     * 组件创建后执行
     */
    open() {
      // 重置搜索条件并搜索
      this.resetSearchParam()
      // 设置 - 部门级联选项
      queryDepartmentList({ multistep: true }).then(res => {
        if (res.code === this.responseSuccessCode) {
          this.departmentOptions = res.data.sysDepartmentList
        } else {
          this.noticeUtil.errorMsg('获取部门级联选项失败')
        }
      })
    },

    /**
     * 查询 - 用户列表
     */
    searchList() {
      this.listLoading = true
      queryUserList(this.listQuery).then(res => {
        if (res.code === this.responseSuccessCode) {
          this.list = res.data.userList
          this.total = res.data.totalCount
        } else {
          this.noticeUtil.errorMsg('获取用户列表失败')
        }

        // 默认选中的用户
        if (this.list && this.list.length > 0 && this.userList && this.userList.length > 0) {
          // 使用$nextTick 在下次DOM更新循环结束之后执行延迟回调
          this.$nextTick(function() {
            for (let i = 0; i < this.userList.length; i++) {
              for (let j = 0; j < this.list.length; j++) {
                if (this.userList[i].userId === this.list[j].userId) {
                  this.$refs.multipleTable.toggleRowSelection(this.list[j], true)
                  break
                }
              }
            }
          })
        }

        // 延迟后清除loading
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },

    /**
     * 重置 - 搜索参数 并重新搜索
     */
    resetSearchParam() {
      this.listQuery.departmentId = ''
      this.listQuery.realName = ''
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.searchList()
    },

    /**
     * 批量添加
     */
    handleAdd() {
      const selectUsers = JSON.parse(JSON.stringify(this.$refs.multipleTable.selection))
      if (selectUsers.length === 0) {
        this.noticeUtil.warningMsg('请选择要添加的用户')
        return
      }
      this.$emit('selectUser', selectUsers)
    },

    // 关闭弹窗
    handleClose() {
      this.$emit('closeDialog')
    }

  }
}
</script>

